<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="记录编码" prop="finaCode">
        <el-input v-model="queryParams.finaCode" placeholder="请输入记录编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="日期" prop="finaDate">
        <!-- <el-date-picker clearable v-model="queryParams.finaDate" type="date" value-format="yyyy-MM-dd" placeholder="日期">
        </el-date-picker> -->
        <el-date-picker type="daterange" v-model="finaDate" format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd" :style="{width: '100%'}" start-placeholder="开始日期" end-placeholder="结束日期"
                  range-separator="至" clearable></el-date-picker>
      </el-form-item>
      <el-form-item label="记账类型" prop="subId1">
        <!-- <el-input v-model="queryParams.subName1" placeholder="请输入记账类型" clearable @keyup.enter.native="handleQuery" /> -->
      <el-select v-model="queryParams.subId1" placeholder="请选择记账类型"  clearable @keyup.enter.native="handleQuery"  @change="getSubListBySubIdSearch(2,queryParams.subId1)">
        <el-option
            v-for="item in sub1Options"
            :key="item.subId"
            :label="item.subName"
            :value="item.subId"
            :disabled="item.delFlag == 'N'"
          ></el-option>
      </el-select>
      </el-form-item>
      <el-form-item label="一级科目" prop="subId2">
        <!-- <el-input v-model="queryParams.subName2" placeholder="请输入一级科目" clearable @keyup.enter.native="handleQuery" /> -->
        <el-select v-model="queryParams.subId2" placeholder="请选择一级科目"  clearable @keyup.enter.native="handleQuery" @change="getSubListBySubIdSearch(3,queryParams.subId2)">
          <el-option
              v-for="item in sub2Options"
              :key="item.subId"
              :label="item.subName"
              :value="item.subId"
              :disabled="item.delFlag == 'N'"
            ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级科目" prop="subId3">
        <el-select v-model="queryParams.subId3" placeholder="请选择二级科目"  clearable @keyup.enter.native="handleQuery" @change="getSubListBySubIdSearch(4,queryParams.subId3)">
          <el-option
              v-for="item in sub3Options"
              :key="item.subId"
              :label="item.subName"
              :value="item.subId"
              :disabled="item.delFlag == 'N'"
            ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="用途" prop="finaAbstractName">
        <el-input v-model="queryParams.finaAbstractName" placeholder="用途(供应商/客户/工资月份)" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="摘要" prop="remark">
        <el-input v-model="queryParams.remark" placeholder="请输入摘要(产品/物料)" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="收入" prop="finaIn">
        <el-input v-model="queryParams.finaIn" placeholder="请输入收入" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="支出" prop="finaOut">
        <el-input v-model="queryParams.finaOut" placeholder="请输入支出" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="经办人" prop="finaOperatorId">
        <el-select v-model="queryParams.finaOperatorId"  placeholder="请输入经办人" clearable
          @keyup.enter.native="handleQuery">
          <el-option
            v-for="dict in dict.type.cash_opter"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="审批状态" prop="apprStatus" v-hasPermi="['mes:fina:cash:check']">
        <el-select v-model="queryParams.apprStatus" placeholder="请选择审批状态" clearable>
          <el-option
            v-for="dict in dict.type.appr_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="申请人" prop="bxRy">
        <el-input v-model="queryParams.bxRy" placeholder="请报销申请人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="申请部门" prop="bxBm">
        <el-input v-model="queryParams.bxBm" placeholder="请报销申请部门" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="付款人" prop="bxFkr">
        <el-input v-model="queryParams.bxFkr" placeholder="请报销付款人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="付款日期" prop="finaPayDate">
        <el-date-picker type="daterange" v-model="finaPayDate" format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd" :style="{width: '100%'}" start-placeholder="付款开始日期" end-placeholder="付款结束日期"
                  range-separator="至" clearable></el-date-picker>
      </el-form-item>


      <el-form-item label="金蝶同步" prop="k3State" >
        <el-select v-model="queryParams.k3State" placeholder="请选择同步状态" clearable>
          <el-option
            v-for="dict in dict.type.k3_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="是否生成借贷" prop="ksIsJd">
        <el-select v-model="queryParams.ksIsJd" placeholder="请选择是否生成借贷" clearable>
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['mes:fina:cash:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['mes:fina:cash:edit']">修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['mes:fina:cash:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleSync"
          v-hasPermi="['mes:fina:cash:sync']">同步数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-upload" size="mini" @click="handleSyncK3Glvoucher"
          v-hasPermi="['mes:fina:cash:syncK3Glvoucher']" v-loading="loading" >上传金蝶</el-button>
          <!-- 同步进度弹窗 -->
                    <el-dialog :visible.sync="syncDialogVisible" title="同步进度" :show-close="false" :close-on-click-modal="false">
                      <div style="text-align: center;">
                        <i class="el-icon-loading"></i>
                        <span style="margin-left: 10px;">同步中，请勿关闭页面...</span>
                        <p style="margin-top: 20px;">已同步 {{ syncProgress }} 条数据</p>
                      </div>
                    </el-dialog>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:fina:cash:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>



        <el-table v-loading="loading" :data="cashList" @selection-change="handleSelectionChange"
        :cell-style="cellStyle">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="记录编码" align="center" prop="finaCode" sortable />
          <el-table-column label="日期" align="center" prop="finaDate" sortable width="80" >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.finaDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="记账类型" align="center" prop="subName1" />
          <el-table-column label="一级科目" align="center" prop="subName2" />
          <el-table-column label="二级科目" align="center" prop="subName3" />
          <el-table-column label="用途" align="center" prop="finaAbstractName"  width="120" >
            <template slot-scope="scope">
              <div class="overflow" :title="scope.row.finaAbstractName">{{scope.row.finaAbstractName}}</div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="客户名称" align="center" prop="cusName" /> -->
          <el-table-column label="经办人" align="center" prop="finaOperatorName" />
          <el-table-column label="收入" align="center" prop="finaIn" />
          <el-table-column label="支出" align="center" prop="finaOut" />
          <el-table-column label="摘要" align="center" prop="remark"  width="120" >
            <template slot-scope="scope">
              <div class="overflow" :title="scope.row.remark">{{scope.row.remark}}</div>
            </template>
          </el-table-column>
          <el-table-column label="审批状态" align="center" prop="apprStatus">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.appr_status" :value="scope.row.apprStatus"/>
            </template>
          </el-table-column>
          <el-table-column label="申请人" align="center" prop="bxRy" />
          <el-table-column label="申请部门" align="center" prop="bxBm" />
          <el-table-column label="付款人" align="center" prop="bxFkr" />
          <el-table-column label="付款日期" align="center" prop="finaPayDate" />
          <el-table-column label="金蝶同步状态" align="center" prop="k3State">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.k3_status" :value="scope.row.k3State"/>
            </template>
          </el-table-column>
          <el-table-column label="是否生成借贷" align="center" prop="ksIsJd">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.ksIsJd"/>
            </template>
          </el-table-column>
          <el-table-column label="凭证" align="center" prop="bxFkPic">
            <template slot-scope="scope">
              <!-- <img width="100%" :src="dialogImageUrl"> -->
              <el-image v-for="(item, index) in scope.row.bxFkPicList" :key="index":src="item" style="width: 30%;"
              :preview-src-list="[item]" >
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center"  class-name="small-padding fixed-width" fixed="right" width="120" >
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-document-copy" @click="handleCopy(scope.row)"
                                   v-hasPermi="['mes:fina:cash:add']">复制</el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"  v-if="scope.row.apprStatus !== '1'"
                v-hasPermi="['mes:fina:cash:edit']">修改</el-button>
              <p v-if="scope.row.apprStatus !== '0'">

              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['mes:fina:cash:edit']">修改</el-button>

              <el-button size="mini" type="text" icon="el-icon-check" @click="checkHandle(scope.row,'0')"
                v-hasPermi="['mes:fina:cash:check']">反审批</el-button>
              </p>
              <p  v-else>
              <el-button size="mini" type="text" style="color: green;" icon="el-icon-check" @click="checkHandle(scope.row,'1')"
                v-hasPermi="['mes:fina:cash:check']">通过</el-button>
              <el-button size="mini" type="text" style="color: red;" icon="el-icon-close" @click="checkHandle(scope.row,'2')"
                v-hasPermi="['mes:fina:cash:check']">不通过</el-button>
              </p>

              <el-button size="mini" type="text" style="color: orange;" icon="el-icon-delete" @click="handleDelete(scope.row)"  v-if="scope.row.apprStatus !== '1'"
                v-hasPermi="['mes:fina:cash:remove']">删除</el-button>

            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />





    <!-- 添加或修改日记账记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="记录编码" prop="finaCode">
              <el-input v-model="form.finaCode" readonly="readonly" maxlength="64" v-if="optType == 'view'"/>
              <el-input v-model="form.finaCode" placeholder="请输入记录编码" maxlength="64" v-else/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item  label-width="80">
              <el-switch v-model="autoGenFlag"
                  active-color="#13ce66"
                  active-text="自动生成"
                  @change="handleAutoGenChange(autoGenFlag)" v-if="optType != 'edit'">
              </el-switch>

            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="日期" prop="finaDate">
              <el-date-picker clearable v-model="form.finaDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="记账类型" prop="subId1">
              <el-select v-model="form.subId1" @change="getSubListBySubId(2,form.subId1)">
                <el-option
                    v-for="item in sub1Options"
                    :key="item.subId"
                    :label="item.subName"
                    :value="item.subId"
                    :disabled="item.delFlag == 'N'"
                  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="一级科目" prop="subId2"  >
              <el-select v-model="form.subId2" @change="getSubListBySubId(3,form.subId2)">
                <el-option
                    v-for="item in sub2Options"
                    :key="item.subId"
                    :label="item.subName"
                    :value="item.subId"
                    :disabled="item.delFlag == 'N'"
                  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="二级科目" prop="subId3">
              <el-select v-model="form.subId3"  @change="getSubListBySubId(4,form.subId3)">
                <el-option
                    v-for="item in sub3Options"
                    :key="item.subId"
                    :label="item.subName"
                    :value="item.subId"
                    :disabled="item.delFlag == 'N'"
                  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经办人" prop="finaOperatorName">
              <el-select v-model="form.finaOperatorName" placeholder="请输入经办人" :disabled="opteratorIsHY">
                <el-option
                  v-for="dict in dict.type.cash_opter"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>

              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="用途" prop="finaAbstractName"  v-show="finaAbstractShow">
              <el-input v-model="form.finaAbstractName" placeholder="请输入用途"/>

            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label-form-item label="摘要" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入摘要" />
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="收入" prop="finaIn" v-show="inShow">
              <el-input v-model="form.finaIn" placeholder="请输入收入(录入数字)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支出" prop="finaOut" v-show="outShow">
              <el-input v-model="form.finaOut" placeholder="请输入支出"/>

            </el-form-item>
          </el-col>
        </el-row>


        <el-row >
          <el-col :span="24">
           <el-form-item label="是否生成借贷">
             <el-radio-group v-model="form.ksIsJd">
               <el-radio
                 v-for="dict in dict.type.sys_yes_no"
                 :key="dict.value"
                 :label="dict.value"
               >{{dict.label}}</el-radio>
             </el-radio-group>
           </el-form-item>
          </el-col>
        </el-row>
        <el-row >
          <el-col :span="12">
            <el-form-item label="申请人" prop="bxRy">
              <el-input v-model="form.bxRy"  placeholder="请输入申请人"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="bxBm">
              <el-input v-model="form.bxBm" placeholder="请输入所属部门"/>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row v-if="form.apprStatus !== '1'">
          <el-col :span="24">
            <el-form-item label="付款日期" prop="finaPayDate">
              <el-date-picker clearable v-model="form.finaPayDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择付款日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row v-if="form.apprStatus !== '1'">
          <el-col :span="12">
            <el-form-item label="付款人" prop="bxFkr">
              <el-input v-model="form.bxFkr" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款状态" prop="bxCnStatus">
              <el-input v-model="form.bxCnStatus" readonly/>
            </el-form-item>
          </el-col>
        </el-row>


        <!-- <el-row v-if="form.apprStatus !== '1'">
          <el-col :span="24">
            <el-form-item label="支付凭证" prop="bxRy">
              <el-image v-for="(item, index) in picList" :key="index":src="item" style="width: 30%;"
              :preview-src-list="[item]" >
              </el-image>
            </el-form-item>
          </el-col>
        </el-row> -->


        <el-row v-if="form.apprStatus !== '1'">
          <el-col :span="24">
            <!--:action里面放图片上传调取的后台方法 :headers设置上传的请求头部,使请求携带自定义token，获取访问权限 -->
            <!--:on-success图片上传成功后的回调方法，用于拿到图片存储路径等信息-->
            <!--:before-upload图片上传前的逻辑判断，例如判断图片大小，格式等-->
            <!--:on-preview图片预览方法 :on-remove图片删除方法   list-type代表文件列表的类型 -->
            <!--file-list存放成功上传图片列表，这里此属性用于修改功能时页面已有图片的显示-->
            <el-form-item label="支付凭证" prop="bxRy">
              <el-upload
            	:action="imgUpload.url"
            	:headers="imgUpload.headers"
            	:on-success="handlePictureSuccess"
            	:before-upload="beforePictureUpload"
            	list-type="picture-card"
            	:file-list="fileListShow"
            	:on-preview="handlePictureCardPreview"
            	:on-remove="handleRemove">
            	<i class="el-icon-plus"></i>
              </el-upload>
              <!--图片预览的dialog-->
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl">
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listCash, getCash, delCash, addCash, updateCash,balanceList,countList,checkCash,syncCash,syncK3Glvoucher } from "@/api/fina/cash";
  import { listSub,listByOrder } from "@/api/fina/sub";
  import {genCode} from "@/api/system/autocode/rule"
  import { getToken } from "@/utils/auth";

  export default {
    name: "Cash",
    dicts: ['appr_status','cash_opter','k3_status','sys_yes_no'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 出纳管理列表格数据
        cashList: [],
        //日期范围
        finaDate: [],
        //日期范围
        finaPayDate: [],
        //出纳统计汇总
        cashBalanceList: [],
        //经办人统计汇总
        countList: [],
        //图片汇总列表
        bxFkPicMap: null,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 收入显示
        inShow:true,
        // 支出显示
        outShow:true,
        // 用途显示
        finaAbstractShow:true,
        // 客户名称显示
        cusNameShow:false,
        //多张凭证
        picList: [],
        syncDialogVisible: false,     // 是否显示同步弹窗
        syncProgress: 0,              // 已同步条数
        pollingTimer: null,            // 轮询定时器
        expectedSyncCount: 0 ,// 保存预计同步条数
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          finaCode: null,
          finaDate: null,
          finaDateStart: null,
          finaDateEnd: null,
          subId1: null,
          subName1:null,
          subId2: null,
          subName2:null,
          subId3: null,
          subName3:null,
          subId4: null,
          subName4:null,
          orderNum: null,
          finaAbstractId: null,
          finaAbstractName: null,
          finaOperatorId: null,
          finaOperatorName: null,
          finaIn: null,
          finaOut: null,
          finaBalance: null,
          status: null,
          bxRy: null,
          bxBm: null,
          bxFkr: null,
          finaPayDate: null,
          finaPayDateStart: null,
          finaPayDateEnd: null,
          k3State: null,
          k3Id: null,
          k3SyncTime: null
        },
        // 表单参数
        form: {
        },
        //弹框的操作类型 view add edit
        optType: undefined,
        //自动生成物料编码标识
        autoGenFlag: false,
        //是否海洋科技
        opteratorIsHY:false,
        //所有科目列表
        subAllOptions:[],
        //科目一列表
        sub1Options: [],
        //科目二列表
        sub2Options: [],
        //科目三列表
        sub3Options: [],
        //科目四列表
        sub4Options: [],
        //科目四列表
        finaAbstractOptions: [],
        //科目一选中id
        sub1IdSel:0,
        //科目2选中id
        sub2IdSel:0,
        //科目3选中id
        sub3IdSel:0,
        //科目4选中id
        sub4IdSel:0,
        //经办人总列表
        cashOpter: [],
        //经办人使用列表
        cashOpterUse: [],
        //经办人-1号仓
        cashOpter1: [],
        //经办人-2号仓
        cashOpter2: [],
        //经办人-借还仓
        cashOpter3: [],
        spanTableRow: {},
        largeImageUrl: '',

        // 表单校验
        rules: {
          finaCode: [
            { required: true, message: "记录编码不能为空", trigger: "blur" },
            { max: 64, message: '记录编码长度必须小于64个字符', trigger: 'blur' }
          ],
          finaDate: [
            { required: true, message: "日期不能为空", trigger: "blur" }
          ],
          subId1: [
            { required: true, message: "记账类型不能为空",trigger: "blur"}
          ],
          subId2: [
            { required: true, message: "一级科目不能为空", trigger: "blur" },
          ],
          subId3: [
            { required: true, message: "二级科目不能为空",trigger: "blur"}
          ],
          // subId4: [
          //   { required: true, message: "四级科目不能为空", trigger: "blur" },
          // ],
          finaAbstractName: [
            { required: false, message: "用途不能为空",trigger: "blur"}
          ],
          finaOperatorName: [
            { required: true, message: "经办人不能为空", trigger: "blur" },
          ],
          finaIn: [
            { required: false, message: "请录入收入金额(精确小数点2为)", trigger: "blur" },
          ],
          finaOut: [
            { required: false, message: "请录入支出金额(精确小数点2为)", trigger: "blur" },
          ],
          // finaIn: [
          //   { required: false, validator:this.isInMoney.bind(this) ,message: "请录入收入金额(精确小数点2为)", trigger: "blur" },
          // ],
          // finaOut: [
          //   { required: false, validator:this.isOutMoney.bind(this) ,message: "请录入支出金额(精确小数点2为)", trigger: "blur" },
          // ],
          // cusName: [
          //   { required: false, message: "客户名称不能为空", trigger: "blur" },
          // ],

        },
        //////////图片上传判断是否有相同图片
        // 文件类型, 例如['png', 'jpg', 'jpeg']
        fileType: {
          type: Array,
          default: () => ["png", "jpg", "jpeg"],
        },
        isCommonName: true,
        //修改时此属性用于接收数据库中图片存储list，图片才能正常显示
        fileListShow: [],
        //页面上存的暂时图片地址List
        fileListPut: [],
        dialogImageUrl: '',
        dialogVisible: false,
        imgUpload: {
            // 设置上传的请求头部
            headers: {
              Authorization: "Bearer " + getToken()
            },
            // 图片上传的方法地址:
            url: process.env.VUE_APP_BASE_API + "/mes/fina/cash/multiPicturesUpload",
            url2: process.env.VUE_APP_BASE_API,
        }
      };
    },
    created() {
      this.getList();
      this.getSubList();
    },
    methods: {
          /** 复制按钮操作 */
          handleCopy(row) {
            this.reset();
            this.optType = "add";
            // 深拷贝行数据
            const copiedRow = JSON.parse(JSON.stringify(row));
            // 清除唯一标识字段
            copiedRow.finaId = null;
            copiedRow.createTime = null;
            copiedRow.createBy = null;
            copiedRow.updateTime = null;
            copiedRow.updateBy = null;
            copiedRow.finaCode = null;

            // 设置表单数据
            this.form = copiedRow;
            this.open = true;
            this.title = "复制日记账记录";

            // 处理科目选择
            if(this.form.subId1) {
              this.getSubListBythis(2, this.form.subId1);
            }
            if(this.form.subId2) {
              this.getSubListBythis(3, this.form.subId2);
            }
            if(this.form.subId3) {
              this.getSubListBythis(4, this.form.subId3);
            }

            // 处理收入支出显示
            if(this.form.subId1 == 101) { // 应收
              this.inShow = true;
              this.outShow = false;
              this.rules.finaIn[0].required = true;
              this.rules.finaOut[0].required = false;
            } else if(this.form.subId1 == 102) { // 应付
              this.inShow = false;
              this.outShow = true;
              this.rules.finaIn[0].required = false;
              this.rules.finaOut[0].required = true;
            }

            // 处理用途显示
            this.finaAbstractShow = true;
            this.rules.finaAbstractName[0].required = false;

            // 处理图片
            this.fileListShow = [];
            if(this.form.bxFkPic !== null && this.form.bxFkPic !== '') {
              let bxPic = this.form.bxFkPic;
              let bxPicArr = bxPic.split(",");
              for(let i=0; i < bxPicArr.length; i++) {
                let pic = bxPicArr[i];
                const newFile = { name: i, url: pic };
                if(pic !== null && pic !== '') {
                  this.picList.push(pic);
                  this.fileListShow.push(newFile);
                }
              }
            }
          },
      /** 查询出纳管理列列表 */
      getList() {
        this.loading = true;
        if(this.finaDate != undefined && this.finaDate != null && this.finaDate.length>0){
          // console.log("finaDate>>>",this.finaDate)
          this.queryParams.finaDateStart = this.finaDate[0]
          this.queryParams.finaDateEnd = this.finaDate[1]
        }
        if(this.finaPayDate != undefined && this.finaPayDate != null && this.finaPayDate.length>0){
          // console.log("finaDate>>>",this.finaDate)
          this.queryParams.finaPayDateStart = this.finaPayDate[0]
          this.queryParams.finaPayDateEnd = this.finaPayDate[1]
        }

        listCash(this.queryParams).then(response => {
          this.cashList = response.rows;
          this.total = response.total;
          this.loading = false;

          this.cashList.forEach(cash=>{
            let picList = []
            let bxFkPic = cash.bxFkPic
            if(bxFkPic!=null && bxFkPic != ''){
                let bxPic = bxFkPic;
                let bxPicArr = bxPic.split(",")
                for(let i=0;i<bxPicArr.length;i++){
                  let pic = bxPicArr[i]
                  if(pic !== null && pic !== ''){
                    picList.push(pic)
                  }
                }
            }
            console.log("cash.bxFkPicList>>>",JSON.stringify(cash.bxFkPicList))
            cash.bxFkPicList = picList
          })
        });

      },
      /** 审批 */
      checkHandle(item,status){
        var data = {"finaId":item.finaId,"apprStatus":status}
        checkCash(data).then(response => {
          this.$modal.msgSuccess("操作成功");
          this.getList();
        });
      },
      getSummaries(res){
        const { columns, data } = res
        // console.log(columns, res);
        const sum = []
        columns.forEach((element, index) => {
          if (index == 1) {
            sum[index] = '合计'
          }
          if (index == 9) {
            //cur.wxAmount  合计对象的数字
             sum[index] = data.reduce((pre, cur) => pre + Number(cur.finaIn), 0)
             sum[index] = sum[index].toFixed(2)
          }
          if (index == 10) {
            //cur.wxAmount  合计对象的数字
             sum[index] = data.reduce((pre, cur) => pre + Number(cur.finaOut), 0)
             sum[index] = sum[index].toFixed(2)
          }
          if (index == 11) {
            //cur.wxAmount  合计对象的数字
             sum[index] = data.reduce((pre, cur) => pre + Number(cur.finaBalance), 0)
             sum[index] = sum[index].toFixed(2)
          }
        });
        return sum

      },
      /** 获取科目下拉列表 */
      getSubList(){
        listSub(null).then(response => {
          // debugger;
          var data = response.rows
          this.subAllOptions = data
          // console.log("data::::",data)
          for(let i=0;i<data.length;i++){
            var item = data[i]
            // console.log("item::::",item)
            var orderNum = item.orderNum
            if(orderNum == 1){
              this.sub1Options.push(item)
            }
            else if(orderNum == 2){
              this.sub2Options.push(item)
            }else if(orderNum == 3){
              this.sub3Options.push(item)
            }else if(orderNum == 4){
              this.sub4Options.push(item)
            }
          }
        });



      },
      /** 根据上一级获取对应下一级列表 */
      getSubListBySubId(row,subId){
        var data = this.subAllOptions
        var subOptions = []
        var subName = ""
        for(let i=0;i<data.length;i++){
          var item = data[i]
          if(item.subId == subId){
            subName = item.subName
          }
          // console.log("item::::",item)
          var orderNum = item.orderNum
          if(row == 2){
            if(item.subId == subId){
              this.form.subName1 = item.subName
            }
          }else if(row == 3){
            if(item.subId == subId){
              this.form.subName2 = item.subName
            }
          }else if(row == 4){
            if(item.subId == subId){
              this.form.subName3 = item.subName
              // if(item.subName == "海洋科技"){
              //   this.form.finaOperatorId = 1001
              //   this.form.finaOperatorName = "海洋科技"
              //   // this.form.finaOperatorName = {"key":1001,"label":"海洋科技","value":1001}
              //   this.opteratorIsHY = true
              //   this.rules.finaOperatorName[0].required = false
              // }
              // else{
              //   this.opteratorIsHY = false
              // //   this.form.finaOperatorName = ""
              //   this.rules.finaOperatorName[0].required = true
              // }
            }

          }else if(row == 5){
              if(item.subId == subId){
                this.form.subName4 = item.subName
              }
          }
          else if(row == 6){
              if(item.subId == subId){
                this.form.finaAbstractName = item.subName
              }
          }
          if(item.parentId == subId){
            subOptions.push(item)
          }

        }

        if(row == 2){

          if(subId == 101){//应收
            this.inShow = true
            this.outShow = false
            this.rules.finaIn[0].required = true
            this.rules.finaOut[0].required = false
            this.form.finaOut = null
          }else if(subId == 102){// 应付
            this.inShow = false
            this.outShow = true
            this.rules.finaIn[0].required = false
            this.rules.finaOut[0].required = true
            this.form.finaIn = null
          }

          this.form.subId2 = null
          this.form.subId3 = null
          this.form.subId4 = null
          // this.form.finaAbstractId = null
          this.form.finaOperatorId = null
          this.sub2Options = subOptions
        }else if(row == 3){
          this.form.subId3 = null
          this.form.subId4 = null
          // this.form.finaAbstractId = null
          this.form.finaOperatorId = null
          this.sub3Options = subOptions
          // if(subName === "应收货款" || subName === "应付工资" || subName === "应付账款"){
            this.finaAbstractShow = true
            this.rules.finaAbstractName[0].required = false
          // }else{
          //   this.finaAbstractShow = false
          //   this.rules.finaAbstractName[0].required = false
          // }


          //设置经办人
          //初始化经办人
          // var cashOpter = this.dict.type.cash_opter
          // this.cashOpterUse = []
          // this.cashOpter1 = []
          // this.cashOpter2 = []
          // this.cashOpter3 = []
          // var cashOpterTemp = []
            // console.log("opt>>>>>",JSON.stringify(cashOpter.length))
          // for(let i=0;i<cashOpter.length;i++){
          //   var opt = cashOpter[i]

          //   // console.log("opt.label>>>>>",opt.label)
          //   if(opt.label === "MK9813"){
          //     this.cashOpter1.push(opt)
          //   }
          //   if(opt.label === "MK5255"){
          //     this.cashOpter1.push(opt)
          //   }
          //   if(opt.label === "MK222"){
          //     this.cashOpter1.push(opt)
          //   }
          //   if(opt.label === "MK收款码"){
          //     this.cashOpter1.push(opt)
          //   }

          //   if(opt.label === "SMK6217"){
          //     this.cashOpter2.push(opt)
          //   }
          //   if(opt.label === "SJM3649"){
          //     this.cashOpter2.push(opt)
          //   }
          //   if(opt.label === "MKXJ"){
          //     this.cashOpter2.push(opt)
          //   }
          //   if(opt.label === "JMXJ"){
          //     this.cashOpter2.push(opt)
          //   }

          //   if(opt.label === "海洋科技" || opt.label === "匠觅公司"){
          //     this.cashOpter3.push(opt)
          //   }
          // }


          // console.log("cashOpter1>>>>>",cashOpterTemp)
          // console.log("cashOpter1>>>>>",this.cashOpter1)
          // console.log("cashOpter2>>>>>",this.cashOpter2)
          // console.log("cashOpter1>>>>>",this.cashOpter3)


          // if(subName.indexOf("1号") != -1){
          //   this.cashOpterUse = this.cashOpter1
          // }else if(subName.indexOf("2号") != -1){
          //   this.cashOpterUse = this.cashOpter2
          // }else if(subName.indexOf("借") != -1 || subName.indexOf("还") != -1){
          //   this.cashOpterUse = this.cashOpter3
          // }

          // console.log("cashOpterUse>>>>>",this.cashOpterUse)


        }else if(row == 4){
          this.form.subId4 = null
          // this.form.finaAbstractId = null
          this.form.finaOperatorId = null
          this.sub4Options = subOptions
        }else if(row == 5){
          // this.form.finaAbstractId = null
          this.form.finaOperatorId = null
          // this.finaAbstractOptions = subOptions
          // console.log("this.finaAbstractOptions",this.finaAbstractOptions)
          // if(this.finaAbstractOptions != null && this.finaAbstractOptions.length > 0){//存在用途
          // console.log("subOptions",this.finaAbstractOptions,"存在用途")
          //   this.finaAbstractShow = true
          //   this.rules.finaAbstractId[0].required = true
          // }else{// 不需要录入用途
          // console.log("subOptions",this.finaAbstractOptions,"不需要录入用途")
          //   this.finaAbstractShow = false
          //   this.rules.finaAbstractId[0].required = false
          // }
          //判断是否存在需要录入客户名称

          if(this.form.subName4 != undefined && this.form.subName4 != null && this.form.subName4 != ""){
            var subNameTemp = this.form.subName4;
            // console.log("subNameTemp",subNameTemp)
            // console.log("this.cusNameShow",this.cusNameShow)
            if(subNameTemp.indexOf("客户") != -1){
            // console.log("subNameTemp",subNameTemp,"需要录入客户")
              this.cusNameShow = true
              this.rules.cusName[0].required = true
            }else{
            // console.log("subNameTemp",subNameTemp,"不需要录入客户")
              this.cusNameShow = false
              this.rules.cusName[0].required = false
            }
          }

        }

      },

      /** 搜索根据上一级获取对应下一级列表 */
      getSubListBySubIdSearch(row,subId){
        var data = this.subAllOptions
        var subOptions = []
        for(let i=0;i<data.length;i++){
          var item = data[i]
          var orderNum = item.orderNum
          if(item.parentId == subId){
            subOptions.push(item)
          }
        }

        if(row == 2){
          this.queryParams.subId2 = null
          this.sub2Options = subOptions
        }else if(row == 3){
          this.queryParams.subId3 = null
          this.sub3Options = subOptions
        }else if(row == 4){
          this.queryParams.subId4 = null
          this.sub4Options = subOptions
        }else if(row == 5){
          // console.log("subOptions>>>>",subOptions)
          // this.queryParams.finaAbstractId = null
          this.finaAbstractOptions = subOptions
        }

      },

      /** 本级列表 */
      getSubListBythis(row,subId){
        var data = this.subAllOptions
        var subOptions = []
        for(let i=0;i<data.length;i++){
          var item = data[i]
          var orderNum = item.orderNum
          if(item.parentId == subId){
            subOptions.push(item)
          }
        }

        if(row == 1){
          this.sub1Options = subOptions
        }else if(row == 2){
          this.sub2Options = subOptions
        }else if(row == 3){
          this.sub3Options = subOptions
        }else if(row == 4){
          this.sub4Options = subOptions
        }else if(row == 5){
          this.finaAbstractOptions = subOptions
        }


      },

      setOperatorName(cashOpte,finaOperatorName){
        this.cashOpter = cashOpte
        for(let i=0;i<cashOpte.length;i++){
          var item = cashOpte[i]
          if(item.value == finaOperatorName){
            this.form.finaOperatorId = item.value
            this.form.finaOperatorName = item.label
            break
          }
        }
        // $forceUpdate()
        console.log("this.form.finaOperatorId>>>",this.form.finaOperatorId)
        console.log("this.form.finaOperatorName>>>",this.form.finaOperatorName)
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          finaId: null,
          finaCode: null,
          finaDate: null,
          subId1: null,
          subName1:null,
          subId2: null,
          subName2:null,
          subId3: null,
          subName3:null,
          subId4: null,
          subName4:null,
          orderNum: null,
          finaAbstractId: null,
          finaAbstractName: null,
          finaOperatorId: null,
          finaIn: null,
          finaOut: null,
          finaBalance: null,
          remark: null,
          status: "0",
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          ksIsJd: 'Y'
        };
        this.picList = []
        this.fileListShow = []
        this.autoGenFlag = false;
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.finaId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加日记账记录";
        this.optType = "add";
        // this.form.finaOperatorName = "海洋科技"
        // this.form.ksIsJd = "Y"
        // console.log(">>>>>>>>",JSON.stringify(this.dict.type.cash_opter))
      },

      /** 新增按钮操作 */
      handleCheck() {
        this.reset();
        this.open = true;
        this.title = "审批日记账记录";
        this.optType = "check";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.optType = "edit";
        const finaId = row.finaId || this.ids
        getCash(finaId).then(response => {
          console.log("response.data>>>",response.data)
          this.form = response.data;
          this.open = true;
          this.title = "修改日记账记录";
          // // console.log("this.form>>>",this.form)
          if(this.form.subId1 == 101){//应收
            this.inShow = true
            this.outShow = false
            this.rules.finaIn[0].required = true
            this.rules.finaOut[0].required = false
            this.form.finaOut = null
          }else if(this.form.subId1 == 102){// 应付
            this.inShow = false
            this.outShow = true
            this.rules.finaIn[0].required = false
            this.rules.finaOut[0].required = true
            this.form.finaIn = null
          }

          this.getSubListBythis(2,this.form.subId1);
          this.getSubListBythis(3,this.form.subId2);
          this.getSubListBythis(4,this.form.subId3);
          this.getSubListBythis(5,this.form.subId4);


            // var subNameTemp = this.form.subName4;
          //   // console.log("subNameTemp",subNameTemp)
          //   // console.log("this.cusNameShow",this.cusNameShow)
          //   if(subNameTemp.indexOf("客户") != -1){
          // //   // console.log("subNameTemp",subNameTemp,"需要录入客户")
          //     this.cusNameShow = true
          //     this.rules.cusName[0].required = true
          //   }else{
          // //   // console.log("subNameTemp",subNameTemp,"不需要录入客户")
          //     this.cusNameShow = false
          //     this.rules.cusName[0].required = false
          //   }
            // console.log("finaAbstractId:::finaAbstractName",this.form.finaAbstractId,this.form.finaAbstractName)
            // var finaAbstractId = this.form.finaAbstractId
            // console.log("subName2::1111》》》》",this.form.subName2)

          // if(this.form.subName2 === "应收货款" || this.form.subName2 === "应付账款" || this.form.subName2 === "应付工资"){
            // console.log("subOptions","存在用途")
            this.finaAbstractShow = true
            this.rules.finaAbstractName[0].required = false
          // }else{
          //   console.log("subOptions","不需要录入用途")
          //   this.finaAbstractShow = false
          //   this.rules.finaAbstractName[0].required = false

          // }

            // this.form.finaAbstractId = finaAbstractId
            // console.log("finaAbstractId",finaAbstractId)
          // this.getSubListBythis(5,this.form.finaAbstractId);
          // this.picList = []
          // this.fileListShow = []
          if(this.form.bxFkPic !== null && this.form.bxFkPic !== ''){
            let bxPic = this.form.bxFkPic;
            let bxPicArr = bxPic.split(",")
            for(let i=0;i<bxPicArr.length;i++){
              let pic = bxPicArr[i]
            console.log("pic>>>",JSON.stringify(pic))
              const newFile = { name: i, url: pic }; // 假设 response.data.url 是新图片地址
              if(pic !== null && pic !== ''){
                this.picList.push(pic)
                this.fileListShow.push(newFile);
              }
            }
          }
          console.log("fileListShow111>>>",this.fileListShow)
        });

      },
      /** 提交按钮 */
      submitForm() {
        if(this.inShow){
          if (!/^\d+(\.\d{0,2})?$/.test(this.form.finaIn)) {
            this.$modal.msgError('请输入正确的收入金额（最多只能保留两位小数）')
            return;
          }
        }

        if(this.outShow){
          if (!/^\d+(\.\d{0,2})?$/.test(this.form.finaOut)) {
            this.$modal.msgError('请输入正确的支出金额（最多只能保留两位小数）')
            return;
          }
        }

        if(this.dict != undefined && this.dict != null){
          var cashOpte = this.dict.type.cash_opter
          var finaOperatorIdTemp = this.form.finaOperatorName
          for(let i=0;i<cashOpte.length;i++){
            var item = cashOpte[i]
            if(item.value == finaOperatorIdTemp){
              this.form.finaOperatorId = item.value
              this.form.finaOperatorName = item.label
              break
            }
          }
        }

        // if(this.form.finaAbstractId != undefined && this.form.finaAbstractId != null){
        //   var finaAbstractId = this.form.finaAbstractName
        //   for(let i=0;i<this.finaAbstractOptions.length;i++){
        //     var item = this.finaAbstractOptions[i]
        //     if(item.value == finaAbstractId){
        //       this.form.finaAbstractId = item.value
        //       this.form.finaAbstractName = item.label
        //       break
        //     }
        //   }
        // }
        // console.log("this.form.finaAbstractId>>>",this.form.finaAbstractId)
        // console.log("this.form.finaAbstractName>>>",this.form.finaAbstractName)
        // console.log("this.form>>>",JSON.stringify(this.form))

        if(this.form.subId1 == 101){//应收
          this.inShow = true
          this.outShow = false
          this.rules.finaIn[0].required = true
          this.rules.finaOut[0].required = false
          this.form.finaOut = null
        }else if(this.form.subId1 == 102){// 应付
          this.inShow = false
          this.outShow = true
          this.rules.finaIn[0].required = false
          this.rules.finaOut[0].required = true
          this.form.finaIn = null
        }

        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.finaId != null) {
              updateCash(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addCash(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const finaIds = row.finaId || this.ids;
        this.$modal.confirm('是否确认删除日记账记录编号为"' + row.finaCode + '"的数据项？').then(function() {
          return delCash(finaIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('/mes/fina/cash/export', {
          ...this.queryParams
        }, `cash_${new Date().getTime()}.xlsx`)
      },
      /** 同步数据按钮操作 */
      handleSync() {
        if(this.loading){
          this.$modal.message("正常进行中，请不要重复点击...")
        }
        this.loading = true;
        this.$modal.confirm('是否确认同步数据？').then(function() {
          return syncCash();
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("同步成功");
        }).catch(() => {});
      },
      /** 同步至金蝶数据按钮操作 */
      handleSyncK3Glvoucher() {
        if(this.loading){
          this.$modal.message("正常进行中，请不要重复点击...")
        }
        this.loading = true;
        var date = this.queryParams
        this.$modal.confirm('是否确认上传金蝶数据？').then(function() {
          return syncK3Glvoucher(date);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("同步成功");
        }).catch(() => {});
      },
      /**
       * 同步至金蝶数据按钮操作
       */
       handleSyncK3Glvoucher() {
         if (this.loading) {
           this.$modal.message("正常进行中，请不要重复点击...");
           return;
         }

         this.loading = true;

         const dateParams = this.queryParams;
         if (!dateParams) {
           this.$modal.message("查询参数不能为空");
           this.loading = false;
           return;
         }

         // 使用 Promise 链替代 async/await
         this.$modal.confirm('是否确认上传金蝶数据？')
           .then(() => {
             this.showSyncProgressDialog();
             return syncK3Glvoucher(dateParams);
           })
           .then(result => {
             if (result.code === 200 && result.data) {
               this.expectedSyncCount = result.data.total || 0;
             }
             this.startPollingProgress();
           })
           .catch(err => {
             if (err === 'cancel') {
               // 用户取消操作，无需报错
               this.closeSyncProgressDialog();
               this.loading = false;
               return;
             }

             console.error('同步出错:', err);
             this.$modal.msgError("同步失败：" + (err.message || "未知错误"));
             this.closeSyncProgressDialog();
             this.loading = false;
           });
       },

           showSyncProgressDialog() {
             this.syncDialogVisible = true;
             this.syncProgress = 0;
           },

           startPollingProgress() {
             const self = this;
             this.pollingTimer = setInterval(async () => {
               try {
                 const res = await getSyncProgress(); // 调用 /api/syncProgress 获取进度

                 if (res.code === 200) {
                   const currentCount = res.data;
                   self.syncProgress = currentCount;

                   if (currentCount >= self.expectedSyncCount) {
                     clearInterval(self.pollingTimer);
                     self.$modal.msgSuccess("同步成功");
                     self.getList();
                     self.closeSyncProgressDialog();
                   }
                 }

               } catch (err) {
                 console.error('获取进度失败', err);
                 clearInterval(self.pollingTimer);
                 self.$modal.msgError("获取进度失败");
                 self.closeSyncProgressDialog();
               }
             }, 5000);
           },

           closeSyncProgressDialog() {
             this.syncDialogVisible = false;
             this.loading = false;
             if (this.pollingTimer) {
               clearInterval(this.pollingTimer);
               this.pollingTimer = null;
             }
           },
      /**
       * 同步至金蝶数据按钮操作
       */
       handleSyncK3Glvoucher() {
                if (this.loading) {
                  this.$modal.message("正常进行中，请不要重复点击...");
                  return;
                }

                this.loading = true;

                const dateParams = this.queryParams;
                if (!dateParams) {
                  this.$modal.message("查询参数不能为空");
                  this.loading = false;
                  return;
                }

                // 使用 Promise 链替代 async/await
                this.$modal.confirm('是否确认上传金蝶数据？')
                  .then(() => {
                    this.showSyncProgressDialog();
                    return syncK3Glvoucher(dateParams);
                  })
                  .then(result => {
                    if (result.code === 200 && result.data) {
                      this.expectedSyncCount = result.data.total || 0;
                    }
                    this.startPollingProgress();
                  })
                  .catch(err => {
                    if (err === 'cancel') {
                      // 用户取消操作，无需报错
                      this.closeSyncProgressDialog();
                      this.loading = false;
                      return;
                    }

                    console.error('同步出错:', err);
                    this.$modal.msgError("同步失败：" + (err.message || "未知错误"));
                    this.closeSyncProgressDialog();
                    this.loading = false;
                  });
              },

                  showSyncProgressDialog() {
                    this.syncDialogVisible = true;
                    this.syncProgress = 0;
                  },

                  startPollingProgress() {
                    const self = this;
                    this.pollingTimer = setInterval(async () => {
                      try {
                        const res = await getSyncProgress(); // 调用 /api/syncProgress 获取进度

                        if (res.code === 200) {
                          const currentCount = res.data;
                          self.syncProgress = currentCount;

                          if (currentCount >= self.expectedSyncCount) {
                            clearInterval(self.pollingTimer);
                            self.$modal.msgSuccess("同步成功");
                            self.getList();
                            self.closeSyncProgressDialog();
                          }
                        }

                      } catch (err) {
                        console.error('获取进度失败', err);
                        clearInterval(self.pollingTimer);
                        self.$modal.msgError("获取进度失败");
                        self.closeSyncProgressDialog();
                      }
                    }, 5000);
                  },

           showSyncProgressDialog() {
             this.syncDialogVisible = true;
             this.syncProgress = 0;
           },

           startPollingProgress() {
             const self = this;
             this.pollingTimer = setInterval(async () => {
               try {
                 const res = await getSyncProgress(); // 调用 /api/syncProgress 获取进度

                 if (res.code === 200) {
                   const currentCount = res.data;
                   self.syncProgress = currentCount;

                   if (currentCount >= self.expectedSyncCount) {
                     clearInterval(self.pollingTimer);
                     self.$modal.msgSuccess("同步成功");
                     self.getList();
                     self.closeSyncProgressDialog();
                   }
                 }

               } catch (err) {
                 console.error('获取进度失败', err);
                 clearInterval(self.pollingTimer);
                 self.$modal.msgError("获取进度失败");
                 self.closeSyncProgressDialog();
               }
             }, 5000);
           },

           closeSyncProgressDialog() {
             this.syncDialogVisible = false;
             this.loading = false;
             if (this.pollingTimer) {
               clearInterval(this.pollingTimer);
               this.pollingTimer = null;
             }
           },
      //自动生成物料编码
      handleAutoGenChange(autoGenFlag){
        // debugger;
        if(autoGenFlag){
          genCode('FINA_CODE').then(response =>{
            // console.log("response>>>>>>",response)
            this.form.finaCode = response;
          });
         }else{
            this.form.finaCode = null;
         }
      },
      cellStyle({ row, column, rowIndex, columnIndex }) {
        if (column.property === 'subName2' ) {
          if (row.subName3 === '海洋科技') {
            return 'color: red;';
          }
        }
        if (column.property === 'subName3' ) {
          if (row.subName3 === '海洋科技') {
            return 'color: red;';
          }
        }
        // if (column.property === 'subName4' ) {
        //   if (row.subName4 === '海洋科技') {
        //     return 'color: red;';
        //   }
        // }
        if (column.property === 'finaOperatorName' ) {
          if (row.finaOperatorName === '海洋科技') {
            return 'color: red;';
          }
        }

        // if (column.property === 'subName3' || column.property === 'finaOperatorName' || column.property === 'subName4' ) {
        //   if (row.finaOperatorName === '海洋科技' || row.subName3 === '海洋科技' || row.subName4 === '海洋科技') {
        //     return 'color: red;';
        //   }
        // }

      },
      tableRowClassName({ row, rowIndex }) {
        if (rowIndex === 0) {
          return 'row1';
        } else if (rowIndex >= 1 && rowIndex <= 6 ) {
          return "row2";
        } else if (rowIndex >= 7 && rowIndex <= 9 ) {
          return "row3";
        }
      },
      arraySpanMethod({ row, column, rowIndex, columnIndex }) {
        // console.log("columnIndex>>",columnIndex)
        if(rowIndex == 0){
           if (![0,1,2].includes(columnIndex)) {
               return [1, 1];
           }
        }
        if(rowIndex >= 1 && rowIndex <=6){
          if (![0,1,2].includes(columnIndex)) {
              return [6, 1];
          }else{
             return [1, 1];
          }
       }
       if(rowIndex >= 7 && rowIndex <=9){
         if (![0,1,2].includes(columnIndex)) {
             return [2, 1];
         }else{
           return [1, 1];
         }
       }
      },

      // 收入金额验证表达式
      isInMoney(rule,value,callback){
        const { required } = rule
          if(!required){
            // console.log("无需收入>>>>>>>>")
            return
          }
          if (value === '') {
            if (required) callback('请输入收入金额')
            else callback()
          } else if (!/^\d+(\.\d{0,2})?$/.test(value)) {
            callback('请输入正确的收入数值（最多只能保留两位小数）')
          } else if (value > 10000000) {
            callback('单次收入不得大于10000000')
          } else {
            callback()
          }
      },
      // 支出金额验证表达式
      isOutMoney(rule,value,callback){
        const { required } = rule

          if(!required){
            console.log("无需支出>>>>>>>>")
            return
          }
          if (value === '') {
            if (required) callback('请输入支出金额')
            else callback()
          } else if (!/^\d+(\.\d{0,2})?$/.test(value)) {
            callback('请输入正确的支出数值（最多只能保留两位小数）')
          } else if (value > 10000000) {
            callback('单次支出不得大于10000000')
          } else {
            value = 0-value
            callback()
          }
      },
      showLargeImage(imageUrl) {
        this.largeImageUrl = imageUrl;
        $('#imageModal').modal('show');
      },
      //图片上传前的相关判断
      beforePictureUpload(file){
        //每次进来初始化 isCommonName 为true
        this.isCommonName = true;
        const isJPG = this.fileType.default(type => {
          if (file.type.indexOf(type) > -1) return true;
          return false;
        })

        const isLt2M = file.size / 1024 / 1024 < 20;
        //判断是否有相同的图片，如何有即提示并添加失败
        if(this.fileListPut.length > 0){
          this.fileListPut.forEach((item,index)=>{
            if(item.name == file.name){
               this.$message.error('已存在相同的图片！');
               this.isCommonName = false;
            }
          })
        }
        if (!isJPG) {
          this.$message.error('请上传图片格式的文件！');
        }
        if (!isLt2M) {
          this.$message.error('上传的图片不能超过20MB!');
        }
        return isJPG && isLt2M && this.isCommonName;
      },
      //图片上传删除
      handleRemove(file, fileList) {
        console.log("fileList>>>",JSON.stringify(fileList))
        console.log("this.fileListPut>>>",JSON.stringify(this.fileListPut))
      //根据传进来删除的file里图片，同时删除保存在fileListPut的相同图片
        if(this.fileListPut.length > 0){
            this.fileListPut = this.fileListPut.filter((item, index)=>{
            return item.url != file.url;
          })
        }
      },
      //图片预览
      handlePictureCardPreview(file) {
        this.dialogVisible = true;
        this.dialogImageUrl = file.url;
      },
      //图片上传成功后的回调
      handlePictureSuccess(res, file){
        this.fileListPut = []
      //设置图片访问路径
        const imgObjectUrl = this.imgUpload.url2 + file.response.imgUrl;
      //这是每个成功上传图片，以对象的形式保存在一个数组中，进而以JSON格式保存在数据库中某个字段里
        let currentFile = {name: '',url: ''};//
        currentFile.name = file.name;
        currentFile.url = imgObjectUrl;
        // console.log("currentFile>>>",JSON.stringify(currentFile))
      //往此数组中保存当前图片对象
        this.fileListPut.push(currentFile);
        // console.log("fileListPut>>>",JSON.stringify(this.fileListPut))
        var bxFkPics = ""
        if(this.fileListPut != null && this.fileListPut.length >0){
          for(var i=0;i<this.fileListPut.length;i++){
            var fileObj = this.fileListPut[i]
            var urlTemp = fileObj.url
            if(bxFkPics == ""){
              bxFkPics = urlTemp
            }else{
              bxFkPics+= ","+urlTemp
            }
          }
        }
        // console.log("bxFkPics>>>",bxFkPics)
        if(this.form.bxFkPic != null && this.form.bxFkPic != ''){
          this.form.bxFkPic += ","+bxFkPics
        }else{
          this.form.bxFkPic = bxFkPics
        }
        // console.log("bxFkPic2222>>>",JSON.stringify(this.form.bxFkPic))
      }

    }
  };
</script>

<style>
.el-table .row1 {
  background: #EAFAF1;
}
.el-table .row2 {
  background: #FDEDEC;
}
.el-table .row3 {
  background: #EBF5FB;
}

.overflow {
  /* 一定要加宽度 */
  width: 100%;
  /* 文字的大小 */
  height: 20px;
  /* 将对象作为弹性伸缩盒子模型显示 */
  display: -webkit-box;
  /* 超出的文本隐藏 */
  overflow: hidden;
  /* 溢出用省略号 */
  text-overflow: ellipsis;
  /* 显示1行，控制显示的行数 */
  -webkit-line-clamp: 1;
  /* 从上到下垂直排列子元素（设置伸缩盒子的子元素排列方式) */
  -webkit-box-orient: vertical;
}
</style>
